package com.luo.bbs.front.webapi.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.luo.bbs.front.webapi.mapper.AdviceMapper;
import com.example.bbs.front.service.IAdviceService;
import com.luo.bbs.front.webapi.pojo.UserLoginPrincipal;
import com.luo.common.exception.BBSServiceException;
import com.luo.common.restful.ResponseCode;
import com.luo.pojo.advice.entity.Advice;
import com.luo.pojo.advice.dto.AdviceDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bin.cn
 * @since 2023-01-19
 */
@Slf4j
@Service
public class AdviceServiceImpl extends ServiceImpl<AdviceMapper, Advice> implements IAdviceService {

    @Autowired
    private AdviceMapper adviceMapper;

    @Override
    public void write(AdviceDTO adviceDTO) {
        if (adviceDTO.getContent()==null || adviceDTO.getContent().length()==0){
            throw new BBSServiceException(ResponseCode.NOT_FOUND,"意见不能为空");
        }
        Advice advice = new Advice();
        BeanUtils.copyProperties(adviceDTO,advice);
        advice.setUserId(getUserId());
        int insert = adviceMapper.insert(advice);
        if (insert!=1){
            throw new BBSServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"系统繁忙！");
        }
        log.debug("发意见");
    }

    @Override
    public Integer countByUser() {
        QueryWrapper<Advice> adviceQueryWrapper = new QueryWrapper<>();
        adviceQueryWrapper.eq("user_id",getUserId());
        Integer integer = adviceMapper.selectCount(adviceQueryWrapper);
        return integer;
    }

    public UserLoginPrincipal getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLoginPrincipal principal = (UserLoginPrincipal) authentication.getPrincipal();
        if (principal == null) {
            throw new BBSServiceException(ResponseCode.UNAUTHORIZED, "未登录！");
        }
        return principal;
    }

    public Integer getUserId() {
        if (getUserInfo() == null) {
            return null;
        }
        return getUserInfo().getId();
    }
}
